package com.bsj.power.common.config.cached;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.bsj.power.common.config.redis.AlarmConstant;
import com.bsj.power.common.config.redis.RedisConstant;
import com.bsj.power.common.constant.NumericalConstants;
import com.bsj.power.common.def.entity.path.Path;
import com.bsj.power.common.def.entity.personGroup.BindGroupData;
import com.bsj.power.common.def.entity.personGroup.BindPersonGroup;
import com.bsj.power.common.def.entity.personGroup.PersonGroup;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import redis.clients.bsj.JedisClusterBSJ;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author LiJiaXin
 * @version 1.0.0
 * @description PathCached
 * @time 2024/5/21 17:14
 */
@Component
public class PathCached {

    @Autowired
    private JedisClusterBSJ jedisClusterBSJ;

    /**
     * 获取围栏信息
     *
     * @param pathId
     * @return com.bsj.power.common.def.entity.path.Path
     * @author ljx
     * @time 2024/5/21 17:21
     */
    public Path hgetPathInfo(Integer pathId) {
        String pathStr = jedisClusterBSJ.hget(RedisConstant.PATH_REDIS_KEY, pathId + "");
        if (pathStr == null) {
            return null;
        }
        return JSON.parseObject(pathStr, Path.class);
    }

    /**
     * 缓存围栏信息
     *
     * @param path
     * @return void
     * @author ljx
     * @time 2024/5/21 17:22
     */
    public void hsetPathInfo(Path path) {
        if (path != null) {
            Long aLong = jedisClusterBSJ.hset(RedisConstant.PATH_REDIS_KEY, path.getPathId() + "", JSON.toJSONString(path));
        }
    }

    /**
     * 删除围栏信息
     *
     * @param pathId
     * @return void
     * @author ljx
     * @time 2024/5/21 17:22
     */
    public void hdelPathInfo(Integer pathId) {
        jedisClusterBSJ.hdel(RedisConstant.PATH_REDIS_KEY, pathId + "");
    }

    /**
     * 根据围栏id集获取围栏信息
     *
     * @param pathIds
     * @return java.util.List<com.bsj.power.common.def.entity.path.Path>
     * @author ljx
     * @time 2024/9/16 19:01
     */
    public List<Path> hgetPathInfoByIds(List<Integer> pathIds) {
        List<Path> paths = new LinkedList<>();
        if (!CollectionUtils.isEmpty(pathIds)) {
            pathIds = pathIds.stream().distinct().collect(Collectors.toList());
            for (Integer pathId : pathIds) {
                String pathStr = jedisClusterBSJ.hget(RedisConstant.PATH_REDIS_KEY, pathId + "");
                if (StringUtils.isNotBlank(pathStr)) {
                    paths.add(JSON.parseObject(pathStr, Path.class));
                }
            }
        }
        return paths;
    }

    /**
     * 获取所有围栏信息
     *
     * @return java.util.List<com.bsj.power.common.def.entity.path.Path>
     * @author ljx
     * @time 2024/5/21 17:25
     */
    public List<Path> hgetAllPathInfo() {
        Map<String, String> pathMap = jedisClusterBSJ.hgetAll(RedisConstant.PATH_REDIS_KEY);
        if (CollectionUtils.isEmpty(pathMap)) {
            return null;
        }
        return pathMap.entrySet().stream().map(value -> {
            return JSON.parseObject(value.getValue(), Path.class);
        }).collect(Collectors.toList());
    }

    /**
     * 获取围栏数量
     *
     * @return java.lang.Integer
     * @author ljx
     * @time 2024/6/7 11:21
     */
    public Long hlenPathInfo() {
        Long hlen = jedisClusterBSJ.hlen(RedisConstant.PATH_REDIS_KEY);
        return hlen != null ? hlen : NumericalConstants.ZERO;
    }

    /**
     * 保存围栏下面的视频设备ID
     *
     * @param pathId  电子围栏ID
     * @param devices 视频设备主键ID集合
     */
    public void saddPathDevice(Integer pathId, List<Long> devices) {
        jedisClusterBSJ.sadd(RedisConstant.PATH_DEVICE_REDIS_KEY + pathId, devices.stream()
                .map(String::valueOf).toArray(String[]::new));
    }

    /**
     * 获取该围栏下面的视频设备ID
     *
     * @param pathId 围栏ID
     * @return
     */
    public List<Long> smemsPathDevice(Integer pathId) {
        Set<String> smembers = jedisClusterBSJ.smembers(RedisConstant.PATH_DEVICE_REDIS_KEY + pathId);
        List<String> list = new ArrayList<>(smembers);
        return list.stream().map(Long::parseLong).collect(Collectors.toList());
    }

    /**
     * 删除围栏下面的视频设备ID
     *
     * @param pathId
     */
    public void delPathDevice(Integer pathId) {
        jedisClusterBSJ.del(RedisConstant.PATH_DEVICE_REDIS_KEY + pathId);
    }

    /**
     * 根据报警状态码获取警情级别
     *
     * @param alarmCode
     * @return
     */
    public Integer hgetAlarmLevel(Integer alarmCode) {
        AtomicReference<Integer> code = new AtomicReference<>(0);
        Map<String, String> map = jedisClusterBSJ.hgetAll(RedisConstant.ALARM_LEVEL_KEY);
        if (CollectionUtils.isEmpty(map)) {
            return code.get();
        }
        map.forEach((key, value) -> {
            JSONArray jsonArray = JSON.parseArray(value);
            List<Integer> list = jsonArray.toJavaList(Integer.class);
            if (list.contains(alarmCode)) {
                code.set(Integer.parseInt(key));
                return;
            }
        });
        return code.get();
    }

    /**
     * 将白名单分组信息按人员信息组装
     * key = 工号
     * value = 组信息 + 人员信息
     *
     * @return
     */
    public Map<String, BindGroupData> hgetAllSuperGroup() {
        //key=组ID value=组信息
        Map<String, String> map = jedisClusterBSJ.hgetAll(RedisConstant.SUPER_GROUP_AUTH);
        if (CollectionUtils.isEmpty(map)) {
            return null;
        }
        Map<String, BindGroupData> result = new HashMap<>();
        map.forEach((key, value) -> {
            PersonGroup personGroup = JSON.parseObject(value, PersonGroup.class);
            //key=工号 value=作业人员或负责人的详细信息
            Map<String, String> personMap = jedisClusterBSJ.hgetAll(RedisConstant.GROUP_PERSONNEL_INFO + key);
            personMap.forEach((k, v) -> {
                BindPersonGroup bindPersonGroup = JSON.parseObject(v, BindPersonGroup.class);
                BindGroupData bindGroupData = BindGroupData.builder()
                        .personGroup(personGroup).bindPersonGroup(bindPersonGroup).build();
                //返回对应的人员工号为key,value是白名单所保存的围栏,资料等信息
                result.put(k, bindGroupData);
            });
        });
        return result;
    }

    /**
     * 获取该楼层是否有负责人在场
     * @param mapId
     * @return 有值代表该楼层有负责人在，空值表示该楼层无负责人
     */
    public String getLeadMapId(Integer mapId) {
        //获取对应楼层下的负责人停留信息
        String leadAlarmStr = jedisClusterBSJ.get(AlarmConstant.MID_LEAD_REMAIN_NOT_ALARM_STATE + mapId);
        if (leadAlarmStr == null) {
            return null;
        }
        return leadAlarmStr;
    }

    /**
     * 保存15秒最新的负责人状态在此区域
     * @param mapId
     * @param perId 负责人ID
     */
    public void setLeadMapId(Integer mapId, Integer perId) {
        String key = AlarmConstant.MID_LEAD_REMAIN_NOT_ALARM_STATE + mapId;
        jedisClusterBSJ.set(key, perId + "");
        jedisClusterBSJ.expire(key, 15);
    }
}
